package ch.nortgram.countdown_worldcup_2014.rss;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import org.xml.sax.Attributes;
import org.xml.sax.helpers.DefaultHandler;

public class Handler extends DefaultHandler
	{
	private Feed Feed;
	private Item Item;
	private StringBuilder stringBuilder;

	@Override
	public void startDocument()
		{
		Feed = new Feed();
		}

	public Feed getResult()
		{
		return Feed;
		}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes)
		{
		stringBuilder = new StringBuilder();

		if(qName.equals("item") && Feed != null)
			{
			Item = new Item();
			Item.setFeed(Feed);
			Feed.addItem(Item);
			}
		if(localName.equals("enclosure"))
			{
			Item.setImage(attributes.getValue("url"));
			}
		}

	@Override
	public void characters(char[] ch, int start, int length)
		{
		stringBuilder.append(ch, start, length);
		}

	@Override
	public void endElement(String uri, String localName, String qName)
		{
		if(Feed != null && Item == null)
			{
			// Parse feed properties

			try
				{
				if (qName != null && qName.length() > 0)
					{
				    String methodName = "set" + qName.substring(0, 1).toUpperCase() + qName.substring(1);
				    Method method = Feed.getClass().getMethod(methodName, String.class);
				    method.invoke(Feed, stringBuilder.toString());
					}
				}
			catch (SecurityException e) {}
			catch (NoSuchMethodException e) {}
			catch (IllegalArgumentException e) {}
			catch (IllegalAccessException e) {}
			catch (InvocationTargetException e) {}
			}
		else if (Item != null)
			{
			// Parse item properties
			try
				{
				if(qName.equals("content:encoded")) 
					{
					qName = "content";
					}
				String methodName = "set" + qName.substring(0, 1).toUpperCase() + qName.substring(1);
				Method method = Item.getClass().getMethod(methodName, String.class);
				method.invoke(Item, stringBuilder.toString());
				}
			catch (SecurityException e) {}
			catch (NoSuchMethodException e) {}
			catch (IllegalArgumentException e) {}
			catch (IllegalAccessException e) {}
			catch (InvocationTargetException e) {}
			}
		}
	}